package com.market.fleamarket.service;

import com.market.fleamarket.entity.Product;
import com.market.fleamarket.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@Service
public class ProductService {
    @Autowired
    private ProductRepository productRepository;

    // 定义有效的商品状态列表，用于处理不同的状态值
    private static final List<String> VALID_PRODUCT_STATUSES = Arrays.asList(
            "on_sale", "ON_SALE", "111", "12", "on sale"
    );

    public Product save(Product product) {
        return productRepository.save(product);
    }

    public List<Product> findAll() {
        return productRepository.findByStatusNot("deleted");
    }

    public Optional<Product> findById(Long id) {
        return productRepository.findById(id);
    }

    /**
     * 删除商品
     * @param id 商品ID
     */
    @Transactional
    public void deleteById(Long id) {
        productRepository.deleteById(id);
    }

    /**
     * 检查商品是否处于可售状态
     * @param product 商品对象
     * @return 如果商品可售返回true，否则返回false
     */
    public boolean isProductSellable(Product product) {
        if (product == null || product.getStatus() == null) {
            return false;
        }

        // 检查商品状态是否在有效状态列表中，且库存大于0
        String status = product.getStatus().toLowerCase();
        return VALID_PRODUCT_STATUSES.stream()
                .map(String::toLowerCase)
                .anyMatch(s -> s.equals(status)) && product.getQuantity() > 0;
    }

    public Page<Product> findByCategory(Long categoryId, Pageable pageable) {
        return productRepository.findByCategory_IdAndStatusNot(categoryId, "deleted", pageable);
    }

    public Page<Product> searchByName(String keyword, Pageable pageable) {
        return productRepository.findByNameContainingAndStatusNot(keyword, "deleted", pageable);
    }

    public Page<Product> findOnSaleValidProducts(Pageable pageable) {
        // 修改为使用动态查询，支持多种商品状态
        LocalDateTime now = LocalDateTime.now();
        return productRepository.findByStatusInAndStatusNotAndValidUntilAfterOrValidUntilIsNull(
                VALID_PRODUCT_STATUSES, "deleted", now, pageable);
    }

    public Page<Product> findAllProducts(Pageable pageable) {
        return productRepository.findByStatusNot("deleted", pageable);
    }

    /**
     * 查询用户发布的所有商品
     * @param userId 用户ID
     * @param pageable 分页信息
     * @return 商品分页数据
     */
    public Page<Product> findByUserId(Long userId, Pageable pageable) {
        return productRepository.findByUser_IdAndStatusNot(userId, "deleted", pageable);
    }

    /**
     * 发布新商品
     * @param product 商品信息
     * @return 保存后的商品
     */
    public Product publishProduct(Product product) {
        // 设置默认状态为待审核
        product.setStatus("pending");
        product.setCreatedAt(LocalDateTime.now());

        // 确保商品数量至少为1
        if (product.getQuantity() == null || product.getQuantity() < 1) {
            product.setQuantity(1);
        }

        return productRepository.save(product);
    }

    /**
     * 更新商品状态
     * @param productId 商品ID
     * @param status 新状态
     * @param userId 操作用户ID (用于验证权限)
     * @return 更新后的商品
     */
    public Product updateProductStatus(Long productId, String status, Long userId) {
        Product product = productRepository.findById(productId)
                .orElseThrow(() -> new RuntimeException("商品不存在"));

        // 验证是否是商品所有者
        if (!product.getUser().getId().equals(userId)) {
            throw new RuntimeException("您没有权限修改此商品");
        }

        // 如果商品处于待审核状态，则不允许直接上架
        if ("pending".equals(product.getStatus()) && "on_sale".equals(status)) {
            throw new RuntimeException("待审核商品不能直接上架，请等待管理员审核");
        }

        product.setStatus(status);
        return productRepository.save(product);
    }

    /**
     * 减少商品库存
     * @param productId 商品ID
     * @param quantity 减少的数量
     * @return 更新后的商品
     * @throws RuntimeException 如果库存不足
     */
    @Transactional
    public Product decreaseStock(Long productId, Integer quantity) {
        Product product = productRepository.findById(productId)
                .orElseThrow(() -> new RuntimeException("商品不存在"));

        if (product.getQuantity() < quantity) {
            throw new RuntimeException("商品库存不足");
        }

        product.setQuantity(product.getQuantity() - quantity);

        // 如果库存为0，则将商品状态更新为售罄
        if (product.getQuantity() == 0) {
            product.setStatus("sold_out");
        }

        return productRepository.save(product);
    }

    /**
     * 增加商品库存
     * @param productId 商品ID
     * @param quantity 增加的数量
     * @return 更新后的商品
     */
    @Transactional
    public Product increaseStock(Long productId, Integer quantity) {
        Product product = productRepository.findById(productId)
                .orElseThrow(() -> new RuntimeException("商品不存在"));

        product.setQuantity(product.getQuantity() + quantity);

        // 如果商品之前是售罄状态，且现在有库存了，则更新为在售状态
        if ("sold_out".equals(product.getStatus()) && product.getQuantity() > 0) {
            product.setStatus("on_sale");
        }

        return productRepository.save(product);
    }

    /**
     * 检查商品库存是否足够
     * @param productId 商品ID
     * @param quantity 需要的数量
     * @return 如果库存足够返回true，否则返回false
     */
    public boolean checkStock(Long productId, Integer quantity) {
        Product product = productRepository.findById(productId).orElse(null);
        return product != null && product.getQuantity() >= quantity;
    }
}